import { recognizeImage } from '../../utils/api'

Page({
  data: {
    showCamera: false
  },

  // 分享配置
  onShareAppMessage() {
    return {
      title: '拍照学英语',
      path: '/pages/camera/camera'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '拍照学英语',
      query: ''
    }
  },

  startCamera() {
    this.setData({
      showCamera: true
    })
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        this.processImage(res.tempFiles[0].tempFilePath)
      },
      fail: (err) => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'error'
        })
      }
    })
  },

  takePhoto() {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({ showCamera: false })
        this.processImage(res.tempImagePath)
      },
      fail: (err) => {
        console.error('拍照失败:', err)
        wx.showToast({
          title: '拍照失败',
          icon: 'error'
        })
      }
    })
  },

  processImage(imagePath) {
    wx.showLoading({
      title: '识别中...',
      mask: true
    })
    
    recognizeImage(imagePath)
      .then(result => {
        if (result.success) {
          wx.navigateTo({
            url: `/pages/result/result?imagePath=${encodeURIComponent(imagePath)}&wordsData=${encodeURIComponent(JSON.stringify(result.data.words))}`
          })
        } else {
          wx.showToast({
            title: result.error,
            icon: 'error'
          })
        }
      })
      .catch(err => {
        console.error('识别失败:', err)
        wx.showToast({
          title: '识别失败',
          icon: 'error'
        })
      })
      .finally(() => {
        wx.hideLoading()
      })
  },

  error(e) {
    console.error('相机错误:', e.detail)
    wx.showToast({
      title: '相机启动失败',
      icon: 'error'
    })
  }
}) 